<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class AfterSalesLogistic extends Model
{
    use HasFactory;

    protected $fillable = [
        'request_id',
        'type',
        'submitted_by',
        'tracking_number',
        'company',
        'status',
        'sent_at',
        'received_at',
        'sender_name',
        'sender_phone',
        'sender_address',
        'receiver_name',
        'receiver_phone',
        'receiver_address',
        'note',
    ];

    protected $casts = [
        'sent_at' => 'datetime',
        'received_at' => 'datetime',
    ];

    // 物流类型常量
    const TYPE_RETURN = 'return';      // 退货物流
    const TYPE_EXCHANGE = 'exchange';   // 换货物流
    
    // 提交者常量
    const SUBMITTED_BY_USER = 'user';   // 用户提交
    const SUBMITTED_BY_ADMIN = 'admin'; // 管理员提交

    /**
     * 关联售后申请
     */
    public function request(): BelongsTo
    {
        return $this->belongsTo(AfterSalesRequest::class, 'request_id');
    }

    /**
     * 获取物流类型文本
     */
    public function getTypeTextAttribute(): string
    {
        return match($this->type) {
            self::TYPE_RETURN => '退货物流',
            self::TYPE_EXCHANGE => '换货物流',
            default => '未知类型',
        };
    }

    /**
     * 获取提交者文本
     */
    public function getSubmittedByTextAttribute(): string
    {
        return match($this->submitted_by) {
            self::SUBMITTED_BY_USER => '用户',
            self::SUBMITTED_BY_ADMIN => '商家',
            default => '未知',
        };
    }

    /**
     * 获取物流状态文本
     */
    public function getStatusTextAttribute(): string
    {
        return match($this->status) {
            'pending' => '待发货',
            'shipped' => '已发货',
            'delivered' => '已送达',
            'cancelled' => '已取消',
            default => '未知状态',
        };
    }

    /**
     * 标记为已发货
     */
    public function markAsShipped(): void
    {
        $this->update([
            'status' => 'shipped',
            'sent_at' => now(),
        ]);
    }

    /**
     * 标记为已送达
     */
    public function markAsDelivered(): void
    {
        $this->update([
            'status' => 'delivered',
            'received_at' => now(),
        ]);
    }
}
